package com.shaoyu.spring.study.validate.core;

import com.shaoyu.spring.study.validate.annotation.ValidateFor;
import com.shaoyu.spring.study.validate.annotation.ValidateIntercept;

import org.apache.commons.collections4.MapUtils;

import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.event.ContextRefreshedEvent;

import org.springframework.core.annotation.AnnotationUtils;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Desc :
 * @Author: shaoyu
 * @Date : 2022/8/23 09:13
 */
@EnableAspectJAutoProxy
@Configuration
public class ValidateAutoConfiguration implements ApplicationListener<ContextRefreshedEvent> {

    @Bean
    public ValidateAspect validateAspect(){
        return new ValidateAspect();
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(ValidateIntercept.class);
        if(MapUtils.isEmpty(beansWithAnnotation)){
            return;
        }
        beansWithAnnotation.values().forEach(bean->{
            Class<?> beanClass = AopUtils.getTargetClass(bean);
            Method[] methods = ReflectionUtils.getDeclaredMethods(beanClass);
            for (Method method : methods) {
                ValidateFor validateFor = AnnotationUtils.findAnnotation(method, ValidateFor.class);
//                ValidateFor validateFor = method.getDeclaredAnnotation(ValidateFor.class);
                if(validateFor == null){
                    continue;
                }
                method.setAccessible(true);
                ValidateInterceptorExecutor.addInterceptor(bean,method,validateFor);
            }
        });
    }
}
